package com.by.base;

/**
 * @version 1.0
 * @Author 彭彦彬
 * @Date 2025/4/9 11:02
 * @注释
 */
import com.by.sql.SqlBuilder;
import com.by.utils.JdbcUtils;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleMapper<T> implements BaseMapper<T> {
    private final Class<T> entityClass;

    public SimpleMapper(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    @Override
    public int insert(T entity) {
        String sql = SqlBuilder.buildInsertSql(entityClass);
        try (Connection conn = JdbcUtils.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            int index = 1;
            for (Field field : entityClass.getDeclaredFields()) {
                field.setAccessible(true);
                stmt.setObject(index++, field.get(entity));
            }
            return stmt.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public int deleteById(Serializable id) {
        return 0;
    }

    @Override
    public int updateById(T entity) {
        return 0;
    }

    @Override
    public T selectById(Serializable id) {
        String sql = SqlBuilder.buildSelectByIdSql(entityClass);
        try (Connection conn = JdbcUtils.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setObject(1, id);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                T entity = entityClass.getDeclaredConstructor().newInstance();
                for (Field field : entityClass.getDeclaredFields()) {
                    field.setAccessible(true);
                    field.set(entity, rs.getObject(field.getName()));
                }
                return entity;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<T> selectList() {
        String sql = SqlBuilder.buildSelectAllSql(entityClass);
        List<T> list = new ArrayList<>();
        try (Connection conn = JdbcUtils.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql);
             ResultSet rs = stmt.executeQuery()) {
            while (rs.next()) {
                T entity = entityClass.getDeclaredConstructor().newInstance();
                for (Field field : entityClass.getDeclaredFields()) {
                    field.setAccessible(true);
                    field.set(entity, rs.getObject(field.getName()));
                }
                list.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
}
